import { Component } from 'react';
import { base } from 'nc-lightapp-front';
const { NCDiv } = base;
import classnames from 'classnames';
import './index.less';

class FuzzyQueryFilter extends Component {
  constructor(props) {
    super();
    this.state = {
      filterData: [],
      currFilterItemIndex: 0
    };
  }

  clearFilterData() {
    this.setState({
      currFilterItemIndex: 0,
      filterData: []
    })
  }

  queryFilterData() {
    let { parentThis: { queryKey }, nameForAll, requestForKey } = this.props;
    let fuzzySearch = queryKey.querycondition.conditions.find((item) => {
      return item.field == 'search'
    });
    if (!fuzzySearch) {
      this.setState({
        filterData: []
      });
    } else {
      requestForKey({
        data: queryKey,
        success: data => {
          if (data.data && data.data.length) {
            data.data.unshift({
              key: nameForAll,
              value: 'All'
            })
          }
          this.setState({
            filterData: data.data
          });
        }
      });
    }
  }

  filterItemClick = (index) => {
    let { parentThis: { queryKey }, parentThis, queryData } = this.props;
    let filterData = this.state.filterData;
    this.setState({
      currFilterItemIndex: index
    });
    queryKey.fuzzyQueryKey = [];
    if (filterData[index].value != 'All') {
      let fuzzySearchValue = queryKey.querycondition.conditions.find((item) => {
        return item.field == 'search'
      });
      let value = '';
      if (fuzzySearchValue) {
        value = fuzzySearchValue.value.firstvalue
      }
      queryKey.fuzzyQueryKey.push(`${filterData[index].value}=${value}`);
    }
    queryData.call(parentThis);
  }

  render() {
    let filterDataJsx = this.state.filterData.map((item, index) => {
      let classVar = index == this.state.currFilterItemIndex  ? 
        'filter-item-checked nc-theme-ztab-area-bgc nc-theme-ztab-font-c' 
          : 
        'nc-theme-otab-area-bgc nc-theme-ztab-ofont-c';
      return (
        <div onClick={() => this.filterItemClick(index)} className={classnames('filter-item ', classVar)}>
          {item.key}
        </div>
      )
    })
    return (
      <NCDiv areaCode={NCDiv.config.SEARCH}
        className={classnames("search-filter-item-wrap nc-theme-gray-area-bgc", { 'search-filter-item-wrap-hide': this.state.filterData.length == 0 })}
      >
        {filterDataJsx}
      </NCDiv>
      
    );
  }
}

export default FuzzyQueryFilter;